<template>
  <div class="map-container">
    <h2>选择位置</h2>
    <div v-if="!apiLoaded" class="map-loading">
      <el-icon class="is-loading">
        <Loading/>
      </el-icon>
      地图加载中...
    </div>
    <div v-show="apiLoaded" id="map" class="map-content"></div>
    <el-button
        @click="confirmLocation"
        type="primary"
        :disabled="!selectedAddress"
    >
      确认位置
    </el-button>
  </div>
</template>

<script setup>
import {ref, onMounted, onUnmounted, nextTick} from 'vue'
import {ElButton, ElIcon} from 'element-plus'
import {Loading} from '@element-plus/icons-vue'

const emit = defineEmits(['locationSelected'])
const props = defineProps({
  lockers: {
    type: Array,
    default: () => []
  }
})

// 响应式状态
const apiLoaded = ref(false)
const selectedAddress = ref('')
const geolocationError = ref(null)
let mapInstance = null
let markerInstance = null
let geocoder = null

// 异步加载高德API
const loadAMapAPI = () => {
  return new Promise((resolve, reject) => {
    if (window.AMap) return resolve()

    window._AMapSecurityConfig = {
      securityJsCode: '9221b56335b28bed688e297a2cb5adc5'
    }

    const script = document.createElement('script')
    script.src = `https://webapi.amap.com/maps?v=2.0&key=c1f44e4d4cb0c571484758199b09b0d9`
    script.onload = () => {
      apiLoaded.value = true
      resolve()
    }
    script.onerror = (err) => {
      console.error('地图脚本加载失败', err)
      reject(err)
    }
    document.head.appendChild(script)
  })
}

// 初始化地图核心逻辑
const initMapCore = async (center) => {
  await nextTick() // 确保DOM更新

  // 初始化地图实例
  mapInstance = new AMap.Map('map', {
    zoom: 13,
    center: center,
    touchZoom: true,
    doubleClickZoom: false
  })

  // 初始化标记
  markerInstance = new AMap.Marker({
    position: center,
    map: mapInstance
  })

  // 添加地图点击监听
  mapInstance.on('click', handleMapClick)

  // 加载地理编码插件
  AMap.plugin('AMap.Geocoder', () => {
    geocoder = new AMap.Geocoder()
  })

  // 添加快递柜标记
  props.lockers.forEach(addLockerMarker)
}

// 处理地图点击事件
const handleMapClick = async (e) => {
  markerInstance.setPosition(e.lnglat)
  try {
    const address = await getAddress(e.lnglat)
    selectedAddress.value = address
  } catch (error) {
    console.error('地址解析失败:', error)
  }
}

// 获取地址信息
const getAddress = (lnglat) => {
  return new Promise((resolve, reject) => {
    geocoder.getAddress(lnglat, (status, result) => {
      if (status === 'complete' && result.info === 'OK') {
        resolve(result.regeocode.formattedAddress)
      } else {
        reject(new Error('地址查询失败'))
      }
    })
  })
}

// 添加快递柜标记
const addLockerMarker = (locker) => {
  new AMap.Marker({
    position: [locker.longitude, locker.latitude],
    map: mapInstance,
    title: locker.name,
    icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png'
  })
}

// 确认位置
const confirmLocation = () => {
  if (selectedAddress.value) {
    emit('locationSelected', selectedAddress.value)
  }
}

// 组件生命周期
onMounted(async () => {
  try {
    await loadAMapAPI()

    // 获取用户位置
    const position = await new Promise((resolve, reject) => {
      navigator.geolocation.getCurrentPosition(resolve, reject, {
        timeout: 5000
      })
    }).catch(() => null)

    const center = position ? [
      position.coords.longitude,
      position.coords.latitude
    ] : [116.397428, 39.90923] // 默认北京坐标

    await initMapCore(center)

  } catch (error) {
    console.error('地图初始化失败:', error)
    geolocationError.value = '地图服务加载失败，请检查网络连接'
  }
})

onUnmounted(() => {
  // 清理地图资源
  if (mapInstance) {
    mapInstance.destroy()
    mapInstance = null
  }
})
</script>

<style scoped>
.map-container {
  width: 100%;
  height: 100%;
  min-height: 500px;
  position: relative;
}

.map-content {
  width: 100%;
  height: 400px;
  border: 1px solid #eee;
  border-radius: 4px;
}

.map-loading {
  height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #666;
  gap: 8px;
}
</style>